<template>
  <div class="search-contain">
    <van-search
      v-model="value"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @cancel="$router.back()"
    />

    <div class="box">
      <div class="history" v-if="historyData.length">
        <div class="content"><span class="title">搜索历史</span><van-icon name="delete-o" @click="clear" /></div>
        <div class="label">
          <span @click="labelSeach($event)" v-for="(item, index) in historyData" :key="index">{{ item }}</span>
        </div>
        <van-divider />
      </div>
      <div class="hot">
        <div class="content">
          <span class="title">热门搜索</span
          ><van-icon :name="isEyeOpen ? 'eye-o' : 'closed-eye'" @click="showorhidden" />
        </div>
        <div class="label" v-if="isEyeOpen">
          <span @click="labelSeach($event)" v-for="(item, index) in hots" :key="index">{{ item }}</span>
        </div>
        <div class="hidden" v-else>已隐藏热门搜索</div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: "",
      isEyeOpen: true,
      historyData: JSON.parse(localStorage.getItem("historyData") || "[]"),
      hots: ["iPhone", "华为", "笔记本电脑", "游戏本", "手机"],
    };
  },
  methods: {
    labelSeach(event) {
      this.$router.push(`/searchresult/${event.target.innerText}`);
    },
    async onSearch() {
      if (this.historyData.includes(this.value)) {
        this.historyData = this.historyData.filter((item) => item !== this.value);
        // return;
      }
      if (this.historyData.length === 7) {
        this.historyData.pop();
      }
      await this.historyData.unshift(this.value);

      this.$router.push(`/searchresult/${this.value}`);

      this.value = "";
    },
    clear() {
      this.historyData = [];
    },
    showorhidden() {
      this.isEyeOpen = !this.isEyeOpen;
    },
  },
  watch: {
    historyData: {
      handler(newV) {
        localStorage.setItem("historyData", JSON.stringify(newV));
      },
      deep: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.search-contain {
  background: #fff;
  border-radius: 6px;

  .box {
    padding-bottom: 20px;

    .content {
      display: flex;
      justify-content: space-between;
      padding: 10px;

      .title {
        font-size: 16px;
        font-weight: 700;
      }

      .van-icon {
        font-size: 16px;
      }
    }

    .label {
      display: flex;
      flex-wrap: wrap;

      span {
        padding: 5px 10px;
        margin: 5px;
        font-size: 14px;
        background: #f3f5f6;
        border-radius: 6px;
      }
    }

    .hidden {
      margin-top: 15px;
      font-size: 16px;
      text-align: center;
    }
  }
}
</style>
